/**
 * Created by zn on 17-4-6.
 * email: 312073339@qq.com
 */
'use strict';
import uuid from 'uuid/v1'
import crypto from 'crypto'
import setting from '../setting'

export default class User {

    getUserByEmail (email) {
        var p = new Promise((resolve, reject) => {
            global.mysql.query("select pwd,uid,salt from user where email = ? ",
                [email],
                (err, result) => err? reject(err): resolve(result)
            )
        })
        return p
    }
    addUser ( email, password){

        let salt = crypto.randomBytes(16).toString('hex')
        let pwd =  crypto.pbkdf2Sync(password, salt, 512, 64, 'sha1').toString('hex')
        let uid = uuid()
        let createTime = parseInt(Date.now() / 1000)
        return new Promise((resolve, reject) => {
            global.mysql.query("insert into user (email, pwd, salt, create_time, uid) values (?, ?, ?, ?, ?)",
                [email, pwd, salt, createTime, uid],
                (err, result) => err? reject(err): resolve(result)
            )
        })
    }
    editUserPassword (email, password) {
        let salt = crypto.randomBytes(16).toString('hex')
        let pwd =  crypto.pbkdf2Sync(password, salt, 512, 64, 'sha1').toString('hex')
        return new Promise((resolve, reject) => {
            global.mysql.query("update user set salt = ?,pwd = ? where email = ? ",
                [salt, pwd, email],
                (err, result) => err? reject(err): resolve(result)
            )
        })
    }
    createToken (uid, platform) {
        var token = crypto.randomBytes(16).toString('hex')
        global.redis.set('token-' + uid + '-' + platform, token)
        global.redis.expire('token-' + uid + '-' + platform, 1800)
        return token
    }
    getToken (uid, platform) {
        return new Promise((resolve, reject) => {
            global.redis.get('token-' + uid + '-' + platform, (err, result) => err? reject(err): resolve(result))
        })
    }
    updateTokenTime (uid, platform) {
        global.redis.expire('token-' + uid + '-' + platform, 1800)
    }
    delToken (uid, platform) {
        if(platform == 0){
            setting.platform.forEach(v => global.redis.del('token-' + uid + '-' + v))
        }else{
            global.redis.del('token-' + uid + '-' + platform)
        }
    }
    checkPassword (hash, salt, pwd) {
        return hash == crypto.pbkdf2Sync(pwd, salt, 512, 64, 'sha1').toString('hex')
    }
}